/* eslint-disable default-case */
import React from 'react';
import { message, Row, Modal } from 'antd';
import { getList, applyOnline, declareExport, signHandle } from '@/services/dismiss';
import { getProgress, getDeclList } from '@/services/reduceempsocial';
import downloadFile from '@/utils/utils';
import * as service from '@/services/socket';

export default {
  state: {
    expandForm: false,
    formFieldsValue: {},
    activeKey: '1',
    tabList: [
      { itemCode: '1', itemName: '待办理' },
      { itemCode: '2', itemName: '办理中' },
      { itemCode: '3', itemName: '已办理' },
      { itemCode: '4', itemName: '办理失败' },
    ],
    pageData: {
      // 列表数据
      list: [],
      pagination: {
        current: 1,
        pageSize: 10,
        total: 10,
      },
    },
    progressPercent: 0,
    showProgress: false,
    declData: {
      data: {
        optDetailsNum: 20,
        pageRecords: [],
        totalCount: 1,
      },
      success: false,
    },
    execStateList: [
      { itemCode: '2', itemName: '待申报' },
      { itemCode: '3', itemName: '网上申报中' },
      { itemCode: '4', itemName: '申报中' },
      { itemCode: '5', itemName: '网上审核中' },
      { itemCode: '7', itemName: '已申报' },
      { itemCode: '8', itemName: '已取消' },
    ],
  },
  effects: {
    // 获取进度
    *getProgress({ payload }, { call, put }) {
      const res = yield call(getProgress, payload);
      if (res.success) {
        yield put({
          type: 'updateModalData',
          payload: {
            progressPercent: res.data.successProp,
          },
        });
      } else {
        // 服务端异常
        message.warning(`${res.message || '查询失败'}`);
      }
      return res;
    },
    // 获取列表
    *getDeclList({ payload }, { call, put }) {
      const res = yield call(getDeclList, payload);
      yield put({
        type: 'updateDeclList',
        payload: res,
      });
      return res;
    },
    // 导出
    *declareExport({ payload }, { call }) {
      const res = yield call(declareExport, payload);
      return res;
    },

    // 标记已办理
    *markDisComplete({ payload }, { put, call, select }) {
      const { current, pageSize } = yield select(state => state.dismiss.pageData.pagination);
      const { formatFormFieldsValue } = yield select(state => state.dismiss);
      const pageArg = { currentPage: current, pageSize };

      const res = yield call(signHandle, payload);
      if (res.success) {
        message.success('操作成功！');
        yield put({
          type: 'fetchList',
          payload: {
            pageArg,
            ...formatFormFieldsValue,
          },
        });
      } else {
        message.warning(res.message || '服务端错误');
      }
      return res;
    },
    *applyOnline({ payload }, { call, put }) {
      const response = yield call(applyOnline, payload);
      yield put({
        type: 'updateModalData',
        payload: {
          batchId: response.data.batchId,
        },
      });
      if (response.success) {
        if (response.data && response.data.successProp !== 100) {
          yield put({
            type: 'updateModalData',
            payload: {
              showProgress: true,
            },
          });
          yield call(service.socketChannel, {
            type: 'sub',
            data: { to: response.data && (response.data.batchId || response.data), type: 'task' },
          });
        } else {
          yield put({
            type: 'updateIndexBatchTask',
            payload: response.data,
          });
        }
      } else {
        // 上传失败
        message.warning(`${response.message || '操作失败：服务端错误'}`);
      }
      return response;
    },
    // 匹配唯一batchId
    *matchBatchId({ payload }, { put, select }) {
      const { batchId } = yield select(state => state.dismiss);
      if (batchId === payload.batchId) {
        yield put({
          type: 'updateIndexBatchTask',
          payload,
        });
      }
    },
    // 更新首页批量任务数据
    *updateIndexBatchTask({ payload }, { put, select }) {
      const { current, pageSize } = yield select(state => state.dismiss.pageData.pagination);
      const { formatFormFieldsValue } = yield select(state => state.dismiss);
      if (payload.successProp === 100) {
        const pageArg = { currentPage: current, pageSize };
        yield put({
          type: 'fetchList',
          payload: {
            pageArg,
            ...formatFormFieldsValue,
          },
        });
        if (payload.errorCount > 0) {
          Modal.warning({
            title: (
              <Row>
                <Row>以下数据为不可办理数据，请下载查看。</Row>
                <a
                  onClick={() =>
                    downloadFile(
                      { batNo: payload.batchId },
                      '/osApi/insDeduDetExt/syncInsOnLineRetiredDeclErrMessage',
                      'POST'
                    )
                  }
                >
                  下载
                </a>
              </Row>
            ),
            okText: '关闭',
            okType: 'default',
            autoFocusButton: 'cancel',
          });
        } else {
          message.success('操作成功！');
        }
        yield put({
          type: 'updateModalData',
          payload: {
            showProgress: false,
          },
        });
      }
    },
    // 首页查找列表
    *fetchList({ payload }, { call, put }) {
      const response = yield call(getList, payload);
      const {
        pageArg: { currentPage, pageSize },
      } = payload;
      if (response.success) {
        yield put({
          type: 'getList',
          payload: {
            data: response.data,
            currentPage,
            pageSize,
          },
        });
      } else {
        message.warning(response.message || '服务端错误');
      }
    },
  },

  reducers: {
    // 获取列表
    getList(
      state,
      {
        payload: { data, currentPage, pageSize },
      }
    ) {
      const list = Array.isArray(data.pageRecords) ? data.pageRecords : [];
      return {
        ...state,
        pageData: {
          list,
          pagination: { total: data.totalCount, current: currentPage, pageSize },
        },
      };
    },
    // 更新列表
    updateDeclList(state, { payload }) {
      return {
        ...state,
        declData: payload,
      };
    },
    // 更新数据 state
    updateModalData(state, { payload }) {
      return {
        ...state,
        ...payload,
      };
    },
  },
  subscriptions: {
    socket({ dispatch }) {
      return service.listen(action => {
        switch (action.type) {
          case 'task':
            dispatch({
              type: 'matchBatchId',
              payload: action.data,
            });
            // 全局保存
            dispatch({
              type: 'publicdata/updateBatchTaskData',
              payload: action.data,
            });
            break;
        }
      });
    },
  },
};
